<?php if(!defined('XCENTER_ROOT')) exit('Access Denied');
/**
 * Created by openXtiger.org.
 * User: xtiger
 * Date: 2009-5-11
 * Time: 16:08:21
 */
include_once XCENTER_ROOT.'xcapi.mysql.php';

define('XC_URL', strtolower((isset($_SERVER['HTTPS'])  ? 'https' : 'http').'://'.$_SERVER['HTTP_HOST'].substr($_SERVER['PHP_SELF'], 0, strrpos($_SERVER['PHP_SELF'], '/'))));
define('MAGIC_QUOTES_GPC', get_magic_quotes_gpc());
define('XC_USER_CHECK_USERNAME_FAILED', -1);
define('XC_USER_USERNAME_BADWORD', -2);
define('XC_USER_USERNAME_EXISTS', -3);
define('XC_USER_EMAIL_FORMAT_ILLEGAL', -4);
define('XC_USER_EMAIL_ACCESS_ILLEGAL', -5);
define('XC_USER_EMAIL_EXISTS', -6);

function xc_user_synlogin($args, $time) {
    global $_xcapi_config,$_xcapi_appid;
    !$_xcapi_appid && $_xcapi_appid = XCENTER_APPID;
    empty($_xcapi_config) && $_xcapi_config = xc_readcache(XCENTER_ROOT.'xcapi.config.php');
    if(!($app = $_xcapi_config[$_xcapi_appid])) {
        exit('Applicaton not exists');
    }
    $uid = $args['uid'];

    if($app['synlogin']) {
        if($user = xmysql_get_user_by_uid($uid)) {
            $synstr = '';
            foreach($_xcapi_config as $appid => $appv) {
                if($appv['synlogin'] && $appv['appid'] != $app['appid']) {
                    $synstr .= '<script type="text/javascript" src="'.$appv['url'].'/api/uc.php?time='.$time.'&code='.urlencode(xc_authcode('action=synlogin&username='.$user['username'].'&uid='.$uid.'&password='.$user['passport']."&time=".$time, 'ENCODE', $appv['authkey'])).'" reload="1"></script>';
                }
            }
            return $synstr;
        }
    }
    return '';
}
function xc_user_synlogout($args, $time) {
    global $_xcapi_config,$_xcapi_appid;
    !$_xcapi_appid && $_xcapi_appid = XCENTER_APPID;
    !$_xcapi_appid && $_xcapi_appid = XCENTER_APPID;
    empty($_xcapi_config) && $_xcapi_config = xc_readcache(XCENTER_ROOT.'xcapi.config.php');
    
    if(!($app = $_xcapi_config[$_xcapi_appid])) {
        exit('Applicaton not exists');
    }
    if($app['synlogin']) {
        $synstr = '';
        foreach($_xcapi_config as $appid => $appv) {
            if($appv['synlogin'] && $appv['appid'] != $app['appid']) {
                $synstr .= '<script type="text/javascript" src="'.$appv['url'].'/api/uc.php?time='.$time.'&code='.urlencode(xc_authcode('action=synlogout&time='.$time, 'ENCODE', $appv['authkey'])).'" reload="1"></script>';
            }
        }
        return $synstr;
    }
    return '';
}

function xc_user_login($args, $time) {
    $isuid = $args['isuid'];
    $username = $args['username'];
    $password = $args['password'];
    $checkques = $args['checkques'];
    $questionid = $args['questionid'];
    $answer = $args['answer'];
    if($isuid) {
        $user = xmysql_get_user_by_uid($username);
    } else {
        $user = xmysql_get_user_by_username($username);
    }
    $passwordmd5 = preg_match('/^\w{32}$/', $password) ? $password : md5($password);
    if(empty($user)) {
        $status = -1;
    } elseif($user['password'] != md5($passwordmd5.$user['salt'])) {
        $status = -2;
    } /*elseif($checkques && $user['secques'] != '' && $user['secques'] != $_ENV['user']->quescrypt($questionid, $answer)) {
        $status = -3;
    }*/ else {
        $status = $user['uid'];
    }
    //$merge = $status != -1 && !$isuid && $_ENV['user']->check_mergeuser($username) ? 1 : 0;
    return array($status, $user['username'], $password, $user['email'], 0);
}

function xc_user_register($args, $time) {
    $username = $args['username'];
    $password =  $args['password'];
    $email = $args['email'];
    $questionid = $args['questionid'];
    $answer = $args['answer'];

    if(($status = xc_check_username($username)) < 0) {
        return $status;
    }
    if(($status = xc_check_email($email)) < 0) {
        return $status;
    }

    $uid = xmysql_add_user($username, $password, $email, 0, $questionid, $answer);
    return $uid;
}
function xc_user_check_username($args, $time){
	return xc_check_email($args['email']);
}
function xc_user_edit($args, $time) {
    $username = $args['username'];
    $oldpw = $args['oldpw'];
    $newpw = $args['newpw'];
    $email = $args['email'];
    $ignoreoldpw = $args['ignoreoldpw'];
    $questionid = $args['questionid'];
    $answer = $args['answer'];

    if(!$ignoreoldpw && $email && ($status = xc_check_email($email, $username)) < 0) {
        return $status;
    }
    $status = xmysql_edit_user($username, $oldpw, $newpw, $email, $ignoreoldpw, $questionid, $answer);

    if($newpw && $status > 0) {
       /* $this->load('note');
        $_ENV['note']->add('updatepw', 'username='.urlencode($username).'&password=');
        $_ENV['note']->send();*/
    }
    return $status;
}
/*private*/
function xc_daddslashes($string, $force = 0, $strip = FALSE) {
	if(!MAGIC_QUOTES_GPC || $force) {
		if(is_array($string)) {
			foreach($string as $key => $val) {
				$string[$key] = xc_daddslashes($val, $force, $strip);
			}
		} else {
			$string = addslashes($strip ? stripslashes($string) : $string);
		}
	}
	return $string;
}
function xc_pget($var, $d='') {
    return !empty($_POST[$var]) ? $_POST[$var] : $d;
}
function xc_serialize($arr, $htmlon = FALSE, $isnormal = FALSE, $level = 1) {
	$s = $level == 1 ? "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\r\n<root>\r\n" : '';
	$space = str_repeat("\t", $level);
	foreach($arr as $k => $v) {
		if(!is_array($v)) {
			$s .= $space."<item id=\"$k\">".($htmlon ? '<![CDATA[' : '').$v.($htmlon ? ']]>' : '')."</item>\r\n";
		} else {
			$s .= $space."<item id=\"$k\">\r\n".xc_serialize($v, $htmlon, $isnormal, $level + 1).$space."</item>\r\n";
		}
	}
	$s = preg_replace("/([\x01-\x09\x0b-\x0c\x0e-\x1f])+/", ' ', $s);
	return $level == 1 ? $s."</root>" : $s;
}

function xc_check_username($username) {
    $username = addslashes(trim(stripslashes($username)));
    if(!xmysql_check_username($username)) {
        return XC_USER_CHECK_USERNAME_FAILED;
    } /*elseif(!$mp('check_usernamecensor',$username)) {
        return XC_USER_USERNAME_BADWORD;
    } */elseif(xmysql_check_usernameexists($username)) {
        return XC_USER_USERNAME_EXISTS;
    }
    return 1;
}
function xc_check_email($email, $username = '') {
    if(!xmysql_check_emailformat($email)) {
        return XC_USER_EMAIL_FORMAT_ILLEGAL;
    } /*elseif(!$mp('check_emailaccess',$email)) {
        return XC_USER_EMAIL_ACCESS_ILLEGAL;
    } */elseif(xmysql_check_emailexists($email, $username)) {
        return XC_USER_EMAIL_EXISTS;
    } else {
        return 1;
    }
}

function xc_authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
    $ckey_length = 4;

    $key = md5($key ? $key : XC_KEY);
    $keya = md5(substr($key, 0, 16));
    $keyb = md5(substr($key, 16, 16));
    $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';

    $cryptkey = $keya.md5($keya.$keyc);
    $key_length = strlen($cryptkey);

    $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
    $string_length = strlen($string);

    $result = '';
    $box = range(0, 255);

    $rndkey = array();
    for($i = 0; $i <= 255; $i++) {
        $rndkey[$i] = ord($cryptkey[$i % $key_length]);
    }

    for($j = $i = 0; $i < 256; $i++) {
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;
        $tmp = $box[$i];
        $box[$i] = $box[$j];
        $box[$j] = $tmp;
    }

    for($a = $j = $i = 0; $i < $string_length; $i++) {
        $a = ($a + 1) % 256;
        $j = ($j + $box[$a]) % 256;
        $tmp = $box[$a];
        $box[$a] = $box[$j];
        $box[$j] = $tmp;
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
    }

    if($operation == 'DECODE') {

        if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
            return substr($result, 26);
        } else {
            return '';
        }
    } else {
        return $keyc.str_replace('=', '', base64_encode($result));
    }

}

function xc_readcache($filename,$have_zlib = 0) {
    $have_zlib && $have_zlib = function_exists("gzinflate");
    $data = file_get_contents($filename);
    if($data && strlen($data)>12) {
        $data = substr($data,12);
        if ($have_zlib) return unserialize(gzinflate($data));
        return unserialize($data);
    }
    return NULL;
}
?>